import 'dart:math';

import 'package:camera/camera.dart';
import 'package:e_reception_flutter/main_delegate.dart';
import 'package:e_reception_flutter/singleton/theme_repository/theme_repository.dart';
import 'package:e_reception_flutter/utils/router_utils.dart';
import 'package:e_reception_flutter/utils/screen_utils.dart';
import 'package:e_reception_flutter/utils/vg_toast_utils.dart';
import 'package:e_reception_flutter/vg_widgets/clip_image_head_border/clip_image_head_border_utils.dart';
import 'package:e_reception_flutter/vg_widgets/vg_photo_preview/vg_photo_preview.dart';
import 'package:e_reception_flutter/vg_widgets/vg_place_holder_status_widget/vg_place_holder_status_widget.dart';
import 'package:flutter/material.dart';
import 'package:matisse_android_plugin/export_matisse.dart';
import 'package:path_provider/path_provider.dart';
import 'package:vg_base/vg_arch_lib.dart';
import 'package:vg_base/vg_string_util_lib.dart';
import 'package:vg_flutter_base_moudle/vg_moudle_widget_lib.dart';

/// 前置摄像头人脸页
///
/// @author: zengxiangxi
/// @createTime: 1/26/21 12:13 PM
/// @specialDemand:
class FrontCameraHeadPage extends StatefulWidget {
  ///路由名称
  static const String ROUTER = "FrontCameraHeadPage";

  @override
  _FrontCameraHeadPageState createState() => _FrontCameraHeadPageState();

  ///跳转方法
  static Future<String> navigatorPush(BuildContext context) {
    return RouterUtils.routeForFutureResult<String>(
      context,
      FrontCameraHeadPage(),
      routeName: FrontCameraHeadPage.ROUTER,
    );
  }
}

class _FrontCameraHeadPageState extends BaseState<FrontCameraHeadPage> {
  ///菜单最大
  static const double _MENU_FIX_HEIGHT = 200;

  CameraController _cameraController;

  CameraLensDirection currentDirection;

  ValueNotifier<PlaceHolderStatusType> _statusValueNotifer;

  double _previewCameraAspectRatio;

  @override
  void initState() {
    super.initState();
    _statusValueNotifer = ValueNotifier(PlaceHolderStatusType.loading);
    initCameraDirection();
  }

  initCameraDirection() {
    bool backResult = setCameraController(CameraLensDirection.back);
    if (backResult) {
      return;
    }
    bool frontResult = setCameraController(CameraLensDirection.front);
    if (frontResult) {
      return;
    }
    Future(() {
      VgToastUtils.toast(context, "没有找到摄像头");
    });
  }

  @override
  void dispose() {
    _cameraController?.dispose();
    _statusValueNotifer?.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.black,
      body: Container(child: _toPlaceStatusWidget()),
    );
  }

  Widget _toPlaceStatusWidget() {
    return ValueListenableBuilder(
      valueListenable: _statusValueNotifer,
      builder: (BuildContext context, PlaceHolderStatusType statusValue,
          Widget child) {
        return VgPlaceHolderStatusWidget(
          loadingStatus: statusValue == PlaceHolderStatusType.loading,
          errorStatus: statusValue == PlaceHolderStatusType.error,
          loadingOnClick: () {
            VgToastUtils.toast(context, "相机初始化中～");
          },
          errorOnClick: () {
            VgToastUtils.toast(context, "相机获取中");
            setCameraController(currentDirection);
          },
          backgroundColor:
              ThemeRepository.getInstance().getCardBgColor_21263C(),
          child: child,
        );
      },
      child: isShowLongLayout() ? _toLongHeightMainWidget() : _toMainWidget(),
    );
  }

  ///普通布局
  Widget _toMainWidget() {
    return Column(
      children: <Widget>[
        _toCameraWidget(),
        Expanded(
          child: _toMenuWidget(),
        )
      ],
    );
  }

  ///适配长手机
  Widget _toLongHeightMainWidget() {
    return Column(
      children: <Widget>[
        Spacer(),
        _toCameraWidget(),
        Container(height: _MENU_FIX_HEIGHT, child: _toMenuWidget()),
      ],
    );
  }

  Widget _toCameraWidget() {
    if (!(_cameraController?.value?.isInitialized ?? false)) {
      return Container(
        height: _getCameraPreviewHeight(),
        child: Center(
          child: Text(
            "初始化...",
            maxLines: 1,
            overflow: TextOverflow.ellipsis,
            style: TextStyle(
              color: Colors.white,
              fontSize: 24,
            ),
          ),
        ),
      );
    }
    return AspectRatio(
      aspectRatio: _cameraController.value.aspectRatio,
      child: Stack(
        fit: StackFit.expand,
        alignment: Alignment.center,
        children: <Widget>[
          CameraPreview(_cameraController),
          Container(
              padding: const EdgeInsets.only(left: 18, right: 18, top: 27),
              child: Image.asset("images/clip_head_camera_ico.png"))
        ],
      ),
    );
  }

  Widget _toMenuWidget() {
    return Container(
      constraints: BoxConstraints.expand(),
      child: Row(
        children: <Widget>[
          Expanded(
            flex: 1,
            child: GestureDetector(
                behavior: HitTestBehavior.translucent,
                onTap: () {
                  RouterUtils.pop(context);
                },
                child: _toCancelButtonWidget()),
          ),
          Expanded(
              flex: 2,
              child: GestureDetector(
                  behavior: HitTestBehavior.translucent,
                  onTap: () {
                    _takePicture();
                  },
                  child: _toTakePicBigButtonWidget())),
          Expanded(
            flex: 1,
            child: GestureDetector(
                behavior: HitTestBehavior.translucent,
                onTap: () {
                  _switchCamera();
                },
                child: _toSwitchCameraButtonWidget()),
          )
        ],
      ),
    );
  }

  Widget _toTakePicBigButtonWidget() {
    return Center(
      child: Container(
        width: 80,
        height: 80,
        alignment: Alignment.center,
        decoration: BoxDecoration(color: Colors.white, shape: BoxShape.circle),
        child: Container(
          width: 70,
          height: 70,
          decoration: BoxDecoration(
              color: Colors.white,
              shape: BoxShape.circle,
              border: Border.all(color: Colors.black, width: 3)),
        ),
      ),
    );
  }

  Widget _toCancelButtonWidget() {
    return Container(
      alignment: Alignment.centerLeft,
      padding: const EdgeInsets.symmetric(horizontal: 15),
      child: Text(
        "取消",
        maxLines: 1,
        overflow: TextOverflow.ellipsis,
        style: TextStyle(
          color: Colors.white,
          fontSize: 16,
        ),
      ),
    );
  }

  Widget _toSwitchCameraButtonWidget() {
    return Container(
      height: 23,
        alignment: Alignment.centerRight,
        padding: const EdgeInsets.symmetric(horizontal: 15),
        margin: const EdgeInsets.symmetric(vertical: 43),
      child: Image.asset(
          "images/fan_zhuan.png",
          color: Colors.white
      ));
  }

  ///拍照
  void _takePicture() async {
    if (_cameraController == null) {
      VgToastUtils.toast(context, "相机初始化中");
      return;
    }
    if (_cameraController.value.isTakingPicture ?? false) {
      VgToastUtils.toast(context, "正在拍照");
      return;
    }
    final dateTime = DateTime.now();
    final String tmpFolderPath = (await getTemporaryDirectory()).path;
    final String imgPath =
        tmpFolderPath + '${dateTime.millisecondsSinceEpoch}.png';
    await _cameraController.takePicture(imgPath);
    String path = await ClipImageHeadBorderUtil.clipOneImage(
      context,
      path: imgPath,
      scaleX: 1,
      scaleY: 1,
      maxAutoFinish: true,
      isShowHeadBorderWidget: true
    );
    print("裁剪后: ${path}");

    ///成功后退出
    if (StringUtils.isNotEmpty(path)) {
      RouterUtils.pop(context, result: path);
    }
  }

  ///切换摄像头
  void _switchCamera() {
    if (currentDirection == null) {
      VgToastUtils.toast(context, "切换异常，无法确认当前镜头");
      return;
    }
    if ((camerasList?.length ?? 0) <= 1) {
      VgToastUtils.toast(context, "设备不支持切换镜头");
      return;
    }
    if (currentDirection == CameraLensDirection.back) {
      setCameraController(CameraLensDirection.front);
    } else if (currentDirection == CameraLensDirection.front) {
      setCameraController(CameraLensDirection.back);
    }
  }

  bool setCameraController(CameraLensDirection direction) {
    if (direction == null) {
      return false;
    }
    if (camerasList == null || camerasList.isEmpty) {
      VgToastUtils.toast(context, "摄像头获取失败");
      return false;
    }

    CameraDescription _description;
    for (CameraDescription item in camerasList) {
      if (item.lensDirection == direction) {
        _description = item;
        break;
      }
    }
    if (_description == null) {
      VgToastUtils.toast(context, "没有找到该镜头");
      return false;
    }
    _cameraController = CameraController(_description, ResolutionPreset.medium);
    //保留当前镜头
    currentDirection = direction;
    // _previewCameraAspectRatio = null;
    _cameraController.initialize().then((_) {
      if (!mounted) {
        return;
      }
      print("打印相机分辨率：${_cameraController?.value?.previewSize}");
      _previewCameraAspectRatio = _cameraController?.value?.aspectRatio;
      _statusValueNotifer?.value = null;
      setState(() {});
    });
    return true;
  }

  double _getCameraPreviewHeight() {
    final double screenW = ScreenUtils.screenW(context);

    return screenW / (_previewCameraAspectRatio ?? (240 / 320));
  }

  ///判断是否显示长屏幕适配
  bool isShowLongLayout() {
    final double screenH = ScreenUtils.screenH(context);
    final double _computePreviewHeight = _getCameraPreviewHeight();

    print("屏幕高度： $screenH");
    print("预览高度：${_computePreviewHeight}");
    if (screenH > (_computePreviewHeight + _MENU_FIX_HEIGHT)) {
      return true;
    } else {
      return false;
    }
  }
}
